<script setup>
import { computed, onMounted, ref } from 'vue'
import {
  getBannersApi,
  addBannerApi,
  modifyBannerApi,
  deleteBannerApi
} from '@/api/banner'
import { getCategoryListApi } from '@/api/category'
import { upload } from '@/api/file'
import { Plus } from '@element-plus/icons-vue'

//tree数据
const treeData = ref([
  { name: '首页', id: 0 },
  { name: '校园圈', campusOrShopType: 1 },
  { name: '店铺圈', campusOrShopType: 2 },
  {
    name: '车辆分类',
    id: -1,
    children: []
  }
])
const setTreeData = async () => {
  const res = await getCategoryListApi()
  treeData.value[3].children = res.data
  // 添加banner表单的选择器
}

// banner数据
const queryParams = ref({
  campusOrShopType: '',
  categoryId: 0
})
const bannerList = ref([])
const setBannerList = async () => {
  const res = await getBannersApi(
    queryParams.value.categoryId,
    queryParams.value.campusOrShopType
  )
  bannerList.value = res.data
  // 缓存数据用于编辑
  bannerList.value.forEach((e) => {
    e.isEdit = false
    e.editRow = {
      linkUri: e.linkUri,
      picture: e.picture
    }
  })
}

// banner图的适配宽度
const adaptWidth = ref(1070)
const adaptHeight = ref(217)
// 添加banner时图片回显的尺寸
const addWidth = computed(() => adaptWidth.value * 0.7)
const addHeight = computed(() => adaptHeight.value * 0.7)
const title = ref('首页Banner')
const treeNodeClick = (obj) => {
  // 如果点击的是车辆分类则啥也不干
  if (obj.id === -1) {
    return
  }
  title.value = obj.name + 'Banner'

  if (obj.id !== 0) {
    adaptWidth.value = 520
    adaptHeight.value = 185
  } else {
    adaptWidth.value = 1070
    adaptHeight.value = 217
  }

  queryParams.value.campusOrShopType = obj.campusOrShopType
  queryParams.value.categoryId = obj.id
  setBannerList()

  // 处理添加表单参数
  if (obj.campusOrShopType) {
    addForm.value.campusOrShopType = obj.campusOrShopType
    addForm.value.categoryId = ''
  } else {
    addForm.value.categoryId = obj.id
    addForm.value.campusOrShopType = ''
  }
}

// 添加banner
const addForm = ref({
  categoryId: 0,
  campusOrShopType: '',
  picture: '',
  linkUri: ''
})
const rule = ref({
  picture: [{ required: true, message: '页面不能为空', trigger: 'blur' }]
})
const addDialogShow = ref(false)
const form = ref(null)
// 取消添加
const closeDialog = () => {
  addDialogShow.value = false
  form.value.resetFields()
}
// 确定添加
const submit = async () => {
  await addBannerApi(addForm.value)
  ElMessage.success('添加成功')
  setBannerList()
  addDialogShow.value = false
}
// 图片格式校验
const beforeAvatarUpload = (rawFile) => {
  if (!['image/jpeg', 'image/jpg', 'image/png'].includes(rawFile.type)) {
    // eslint-disable-next-line no-undef
    ElMessage.error('仅支持上传jpeg、jpg、png格式的图片')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    // eslint-disable-next-line no-undef
    ElMessage.error('请上传小于5M的图片')
    return false
  }
  return true
}
// 上传图片方法，返回图片url
const uploadAvatar = async (file) => {
  const formData = new FormData()
  formData.append('file', file.file)
  const res = await upload(formData)
  addForm.value.picture = res.data
}

// 点击编辑按钮
const bannerEdit = async (item) => {
  item.isEdit = true
}

// 修改图片
const modifyPic = async (uploadFile, item) => {
  const formData = new FormData()
  formData.append('file', uploadFile.file)
  const res = await upload(formData)
  item.editRow.picture = res.data
}

// 提交修改
const saveEdit = async (item) => {
  // 发请求提交修改
  await modifyBannerApi({ id: item.id, ...item.editRow })
  ElMessage.success('修改成功')
  // 重载数据
  setBannerList()
}

// 取消修改
const cancelEdit = (item) => {
  item.isEdit = false
  item.editRow = {
    linkUri: item.linkUri,
    picture: item.picture
  }
}

// 删除banner
const delBanner = (id) => {
  ElMessageBox.confirm('此操作不可逆，确认删除吗', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await deleteBannerApi(id)
    ElMessage.success('删除成功')
    setBannerList()
  })
}

onMounted(() => {
  setBannerList()
  setTreeData()
})
</script>
<template>
  <div class="header-desc">
    <span>banner管理</span>
  </div>
  <div class="container">
    <div class="left">
      <el-tree
        style="width: 150px"
        highlight-current
        default-expand-all
        :data="treeData"
        node-key="categoryId"
        :props="{ children: 'children', label: 'name' }"
        @node-click="treeNodeClick"
      />
    </div>
    <div class="right">
      <div
        style="
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
        "
      >
        <h3 style="font-size: 18px">{{ title }}</h3>
        <el-button type="primary" @click="addDialogShow = true">
          添加banner</el-button
        >
      </div>
      <ul v-if="bannerList.length > 0">
        <li v-for="(banner, index) in bannerList" :key="index">
          <el-card :style="{ width: adaptWidth + 'px' }">
            <template #header>
              <div style="display: flex; justify-content: space-between">
                <span> banner {{ index + 1 }}</span>
                <span v-if="!banner.isEdit">
                  <el-link type="primary" @click="bannerEdit(banner)"
                    >编辑</el-link
                  >
                  <el-link
                    type="danger"
                    style="margin-left: 10px"
                    @click="delBanner(banner.id)"
                    >删除</el-link
                  >
                </span>
                <span v-else>
                  <el-button
                    size="small"
                    type="success"
                    @click="saveEdit(banner)"
                    >保存</el-button
                  >
                  <el-button size="small" @click="cancelEdit(banner)"
                    >取消</el-button
                  >
                </span>
              </div>
            </template>
            <img
              :style="{ height: adaptHeight + 'px' }"
              :src="banner.editRow.picture"
            />
            <div
              style="
                display: flex;
                justify-content: space-between;
                margin-top: 10px;
              "
            >
              <div style="flex: 1">
                <el-text
                  style="margin-right: 5px; position: relative; top: 2px"
                >
                  链接 :
                </el-text>
                <el-input
                  v-if="banner.isEdit"
                  style="max-width: 330px"
                  v-model="banner.editRow.linkUri"
                  size="small"
                ></el-input>
                <el-link
                  v-else
                  :href="banner.linkUri"
                  target="_blank"
                  type="primary"
                >
                  {{ banner.linkUri }}
                </el-link>
              </div>
              <el-upload
                v-if="banner.isEdit"
                action=""
                :show-file-list="false"
                :http-request="(uploadFile) => modifyPic(uploadFile, banner)"
              >
                <el-button size="small" type="primary">上传banner</el-button>
              </el-upload>
            </div>
          </el-card>
        </li>
      </ul>
      <template v-else>
        <el-empty :image-size="200" />
      </template>
    </div>
  </div>
  <el-dialog
    title="添加banner"
    width="860"
    v-model="addDialogShow"
    @close="closeDialog"
  >
    <el-form ref="form" :model="addForm" :rules="rule" label-width="90px">
      <el-form-item label="链接" prop="linkUri">
        <el-input
          v-model="addForm.linkUri"
          style="width: 300px"
          size="small"
        ></el-input>
      </el-form-item>
      <el-form-item label="banner图" prop="picture">
        <el-upload
          class="avatar-uploader"
          action=""
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :http-request="uploadAvatar"
        >
          <img
            v-if="addForm.picture"
            :src="addForm.picture"
            class="bannerImg"
            :style="{ width: addWidth + 'px', height: addHeight + 'px' }"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.bannerImg {
  object-fit: cover;
  display: block;
}
.header-desc {
  border-bottom: 1px solid #ddd;
  padding: 15px 20px;
  background-color: #fff;
}
.container {
  background-color: #fff;
  padding: 20px;
  min-height: 650px;
  display: flex;

  .left {
    margin-right: 20px;
  }

  .right {
    flex: 1;
    ul {
      display: flex;
      flex-wrap: wrap;
      justify-content: space-between;

      li {
        margin-bottom: 10px;
        img {
          width: 100%;
          object-fit: cover;
        }
      }
    }
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
</style>
